package com.gxan.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.wf.captcha.SpecCaptcha;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //引入pom文件的工具类创建（验证码图片）对象
        SpecCaptcha specCaptcha = new SpecCaptcha(120,40,4);
        //获取到验证码的值
        String verificationCode = specCaptcha.text();
        //获取到的验证码存入到session中
        HttpSession session = request.getSession();
        session.setAttribute("verificationCode",verificationCode);
        //将生成的验证码传给前端页面显示
        HashMap<String, Object> map = new HashMap<>();
        map.put("image",specCaptcha.toBase64());
        //System.out.println(specCaptcha.toBase64());
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(map));
        response.getWriter().close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
